package com.atguigu.guli.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.guli.service.base.handler.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectExcelData;
import com.atguigu.guli.service.edu.listener.SubjectExcelDataListener;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author leo
 * @since 2021-11-24
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {
    @Autowired
    SubjectExcelDataListener listener ;
    @Override
    public void importSubject(MultipartFile file) {
        try {
            //对导入的excel文件进行读取解析
            EasyExcel.read(file.getInputStream())
                    .head(SubjectExcelData.class)
                    .sheet(0)
                    .registerReadListener(listener)
                    .doRead();
        } catch (Exception e) {
            throw new GuliException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR,e) ;
        }
    }

    @Override
    public List<Subject> getNestedSubjects() {
        List<Subject> subjects = baseMapper.selectList(null);
        Map<String,Subject> map = new HashMap<>() ;

        subjects.forEach(subject -> {
            if ("0".equals(subject.getParentId())) {
                //是父分类
                map.put(subject.getId(),subject) ;
            }
        });
        subjects.forEach(subject -> {
            if (!"0".equals(subject.getParentId())) {
                //是子分类，从map中取对应父分类
                Subject pSubject = map.get(subject.getParentId());
                if (pSubject != null) {
                    pSubject.getChildren().add(subject);
                }
            }
        });

        return new ArrayList<>(map.values());
    }
}
